#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import yaml
import logging
import argparse
from .cloud_api import CloudAPI
from .workspace import WorkspaceManager

def setup_logging(log_file=None):
    """
    配置日志
    """
    log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    logging.basicConfig(
        level=logging.INFO,
        format=log_format,
        handlers=[
            logging.StreamHandler(),
            logging.FileHandler(log_file) if log_file else logging.NullHandler()
        ]
    )

def load_config(config_file):
    """
    加载配置文件
    """
    try:
        with open(config_file, 'r') as f:
            return yaml.safe_load(f)
    except Exception as e:
        logging.error(f"Failed to load config file: {e}")
        sys.exit(1)

def main():
    parser = argparse.ArgumentParser(description='Tencent Cloud Workspace Manager')
    parser.add_argument('-c', '--config', default='config/config.yaml',
                      help='Path to configuration file')
    parser.add_argument('-l', '--log', default='logs/workspace_manager.log',
                      help='Path to log file')
    args = parser.parse_args()

    # 确保日志目录存在
    os.makedirs(os.path.dirname(args.log), exist_ok=True)
    setup_logging(args.log)
    
    # 加载配置
    config = load_config(args.config)
    
    try:
        # 初始化API客户端
        api = CloudAPI(
            secret_id=config['tencent_cloud']['secret_id'],
            secret_key=config['tencent_cloud']['secret_key'],
            region=config['tencent_cloud'].get('region', 'ap-guangzhou')
        )
        
        # 获取目标工作空间标识
        target_workspace = config['workspace'].get('space_key', '').strip()
        
        # 如果未配置space_key，则列出所有工作空间信息并退出
        if not target_workspace:
            WorkspaceManager.list_workspaces(api)
            sys.exit(0)
        
        # 创建并运行工作空间管理器
        manager = WorkspaceManager(
            api=api,
            target_workspace=target_workspace,
            check_interval=config['workspace'].get('check_interval', 300)
        )
        
        manager.run()
        
    except KeyboardInterrupt:
        logging.info("Program terminated by user")
        sys.exit(0)
    except Exception as e:
        logging.error(f"Program error: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main() 